//
//  XYPlayerView.m
//  PreviewStudyManage
//
//  Created by 吴桑 on 2017/8/10.
//  Copyright © 2017年 lange. All rights reserved.
//

#import "XYPlayerView.h"
#import <IJKMediaFramework/IJKMediaFramework.h>
#import <Masonry/Masonry.h>
#import "BrightnessVolumeView.h"
#import "AppDelegate.h"
#define ScreenBounds            ([UIScreen mainScreen].bounds)
#define ScreenWidth             ScreenBounds.size.width
#define ScreenHeight            ScreenBounds.size.height
@interface XYPlayerView ()<UIGestureRecognizerDelegate>
//
@property (nonatomic, strong) AppDelegate *myDelegate;

//工具栏
@property (nonatomic, strong) UIButton *btnPlay;//播放按钮
@property (nonatomic, strong) BrightnessVolumeView *systemView;
@property (nonatomic, strong) UILabel *labCurrentTime;//当前时间
@property (nonatomic, strong) UILabel *labTotalTime;//全部时长
@property (nonatomic, strong) UISlider *slider;//滑块
@property (nonatomic, strong) UIButton *btnFullScreen;//全屏按钮
@property (nonatomic, strong) UIImageView *imgPlaceHolder;

/** 字幕开关 */
@property (nonatomic, strong) UIButton *btnSubtitle;

//标题栏
@property (nonatomic, strong) UIView *coverView;//整个遮蔽view
@property (nonatomic, strong) UIButton *btnBack;//返回按钮（全屏）
@property (nonatomic, strong) UILabel *labName;//资料名称

//菊花
@property (nonatomic, strong)  UIActivityIndicatorView *activity;

//计时器
@property (nonatomic, weak) NSTimer *timer;

//播放器视图
@property (nonatomic, strong) UIView *playerView;//视频View

//新增字幕匹配
@property (nonatomic, strong) UILabel *subtitleLab;//字幕按钮
@property (nonatomic, strong) NSMutableArray *subtitleArr;//字幕
@property (nonatomic, strong) NSMutableArray *beginTimeSubArr;//字幕开始时间
@property (nonatomic, strong) NSMutableArray *endTimeSubArr;//字幕结束时间

//音频
@property (nonatomic, strong) UIImageView *imgListen;
@property (nonatomic, assign) BOOL isListenType;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger currentIndex;


@property (nonatomic, assign) BOOL isFullScreenNow;
@property (nonatomic, assign) CGFloat totalVideoTime;//视频总时长;

@property (nonatomic, strong) IJKFFOptions *options;
@property (nonatomic, strong) IJKFFMoviePlayerController *player;
@end

@implementation XYPlayerView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        //播放器初始设置
        self.isFullScreenNow = NO;
        self.myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        self.myDelegate.allowRotation = YES;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    }
    return self;
}

- (void)setUrl:(NSString *)url{
    _url = url;
    self.totalVideoTime = 0.0;
    self.isListenType = NO;
    //区分音频还是视频
    if ([[url lowercaseString] containsString:@".mp3"] || [[url lowercaseString] containsString:@".wav"]){
        self.isListenType = YES;
        [self creatVideoUI];
    }else{
        [self initIJKSetting];
        [self creatPlayerUI];
        _subtitleLab.hidden = YES;
        _btnSubtitle.hidden = YES;
    }
}

#pragma mark -创建音频UI
- (void)creatVideoUI{
    
}

#pragma mark -创建视频UI
- (void)initIJKSetting{
    
}

- (void)fullScreen:(UIButton *)sender {
    NSLog(@"点击全屏");
//    if (self.XYPlayerFullScreenBlock) {
//        self.XYPlayerFullScreenBlock(self.isFullScreenNow);
//    }
    [self changeToFullScreen:!self.isFullScreenNow];
}

//是否全屏（横屏）
- (void)changeToFullScreen:(BOOL)isTofull{
    if (isTofull) {
        //变为全屏
        [UIView animateWithDuration:0.25 animations:^{
            NSNumber * value  = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }];
        
    }else  {
        //变为竖屏
        [UIView animateWithDuration:0.25 animations:^{
            NSNumber *value  = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }];
        
    }
}



- (void)statusBarOrientationChange:(NSNotification *)notification{
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationLandscapeRight || orientation ==UIInterfaceOrientationLandscapeLeft) // home键靠右// home键靠左
    {
        
        NSLog(@"强制横屏");
        self.isFullScreenNow = YES;
        [self.ownController.navigationController setNavigationBarHidden:YES animated:YES];
        [UIView animateWithDuration:0.25 animations:^{
            self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
            self.player.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        }];
        self.isFullScreenNow = YES;
        self.btnBack.hidden = NO;
        self.labName.hidden = NO;
        self.btnFullScreen.selected = YES;
        [self.btnFullScreen setImage:[UIImage imageNamed:@"studyStu_hengping"] forState:UIControlStateSelected];
    }else if (orientation == UIInterfaceOrientationPortrait) {
        NSLog(@"强制竖屏");
        self.isFullScreenNow = NO;
        [self.ownController.navigationController setNavigationBarHidden:NO animated:YES];
        [UIView animateWithDuration:0.25 animations:^{
            self.frame = CGRectMake(0, self.topSpace, ScreenWidth, self.playerHeight);
            self.player.view.frame = self.playerView.frame;
        }];
        self.isFullScreenNow = NO;
        self.btnBack.hidden = YES;
        self.labName.hidden = YES;
        self.btnFullScreen.selected = NO;
        [self.btnFullScreen setImage:[UIImage imageNamed:@"studyStu_shuping"] forState:UIControlStateNormal];
    }else if (orientation == UIInterfaceOrientationPortraitUpsideDown)  {
                NSLog(@"其他");
    }
    if (self.delegate &&[self.delegate respondsToSelector:@selector(XYPlayerViewDelegateWithIsFull:)]) {
        [self.delegate XYPlayerViewDelegateWithIsFull:self.isFullScreenNow];
    }

}

- (IJKFFOptions *)options{
    if (!_options) {
        IJKFFOptions *options = [IJKFFOptions optionsByDefault];
        [options setOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_frame" ofCategory:kIJKFFOptionCategoryCodec];
        [options setOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_loop_filter" ofCategory:kIJKFFOptionCategoryCodec];
        [options setOptionIntValue:2 forKey:@"videotoolbox" ofCategory:kIJKFFOptionCategoryPlayer];
//        [options setOptionIntValue:0 forKey:@"videotoolbox" ofCategory:kIJKFFOptionCategoryPlayer];
        [options setOptionIntValue:60 forKey:@"max-fps" ofCategory:kIJKFFOptionCategoryPlayer];
        // 置音量大小，256为标准  要设置成两倍音量时则输入512，依此类推
        [options setPlayerOptionIntValue:256 forKey:@"vol"];
        _options = options;
    }
    return _options;
}
- (IJKFFMoviePlayerController *)player{
    if (!_player) {
        NSURL *urll = [NSURL URLWithString:[self.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
        _player = [[IJKFFMoviePlayerController alloc]initWithContentURL:urll withOptions:self.options];
        [_player setScalingMode:IJKMPMovieScalingModeFill];
        [self installMovieNotificationObservers];
    }
    return _player;
}

- (void)creatPlayerUI{
//    IJKFFOptions *options = [IJKFFOptions optionsByDefault];
//    [options setOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_frame" ofCategory:kIJKFFOptionCategoryCodec];
//    [options setOptionIntValue:IJK_AVDISCARD_DEFAULT forKey:@"skip_loop_filter" ofCategory:kIJKFFOptionCategoryCodec];
//    [options setOptionIntValue:0 forKey:@"videotoolbox" ofCategory:kIJKFFOptionCategoryPlayer];
//    [options setOptionIntValue:60 forKey:@"max-fps" ofCategory:kIJKFFOptionCategoryPlayer];
//    [options setPlayerOptionIntValue:256 forKey:@"vol"];
    
//    NSString *playUrl = [self.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    NSURL *url = [NSURL URLWithString:playUrl];
//    self.player = [[IJKFFMoviePlayerController alloc]initWithContentURL:url withOptions:self.options];
//    [self.player setScalingMode:IJKMPMovieScalingModeFill];
//    [self installMovieNotificationObservers];
    if (![self.player isPlaying]) {
        [self.player prepareToPlay];
    }
    //获取播放视图
    self.playerView = [self.player view];
    
    
    [self addSubview:self.playerView];
    [self.playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    
    //    self.playerView.frame = self.bounds;
    //把播放器插到最上面去
//    [self insertSubview:self.playerView atIndex:0];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(playerViewTap:)];
    tap.delegate = self;
    [self.playerView addGestureRecognizer:tap];
    
    //字幕按钮(放置在工具视图上方)
    [self.playerView addSubview:self.subtitleLab];
    [self.subtitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.playerView);
        make.height.mas_equalTo(45);
    }];
    
    //遮盖view
    [self.playerView addSubview:self.coverView];
    [self.coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.playerView);
    }];
    
    [self.playerView addSubview:self.systemView];
    [self.systemView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.playerView);
        make.top.equalTo(self.playerView.mas_top).offset(40);
        make.bottom.equalTo(self.playerView.mas_bottom).offset(-40);
    }];
    /***********************************************************/
    //返回按钮
    [self.coverView addSubview:self.btnBack];
    [self.btnBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.coverView);
        make.top.equalTo(self.coverView).offset(10);
        make.width.height.mas_equalTo(40);
    }];
    
    //视频名称
    self.labName.text = self.resName;
    [self.coverView addSubview:self.labName];
    [self.labName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.btnBack.mas_right);
        make.centerY.equalTo(self.btnBack);
    }];
    
    /***********************************************************/
    //工具栏播放按钮
    //字幕按钮
    [self.coverView addSubview:self.btnSubtitle];
    [self.btnSubtitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.coverView.mas_top).offset(10);
        make.right.equalTo(self.coverView.mas_right).offset(-10);
        make.height.mas_equalTo(50);
        make.width.height.mas_equalTo(45);
    }];
    
    //全屏按钮
    self.isFullScreenNow = NO;
    [self.coverView addSubview:self.btnFullScreen];
    [self.btnFullScreen mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.coverView);
        make.width.height.mas_equalTo(40);
    }];
    //当前时间
    [self.coverView addSubview:self.labCurrentTime];
    [self.labCurrentTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.coverView).offset(10);
        make.centerY.equalTo(self.btnFullScreen);
        make.width.mas_equalTo(65);
    }];
    //视频总时长
    [self.coverView addSubview:self.labTotalTime];
    [self.labTotalTime mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.btnFullScreen.mas_left);
        make.centerY.equalTo(self.btnFullScreen);
        make.width.mas_equalTo(65);
    }];

    //滑块
    [self.coverView addSubview:self.slider];
    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.labCurrentTime.mas_right).offset(5);
        make.right.equalTo(self.labTotalTime.mas_left).offset(-5);
        make.centerY.equalTo(self.btnFullScreen);
        
    }];
    self.slider.minimumTrackTintColor = [UIColor whiteColor];
    self.slider.maximumTrackTintColor = [UIColor groupTableViewBackgroundColor];
    UIImage *image = [self createImageWithColor:[UIColor whiteColor]];
    UIImage *circleImage = [self circleImageWithImage:image borderWidth:0 borderColor:[UIColor clearColor]];
    [self.slider setThumbImage:circleImage forState:UIControlStateNormal];
    [self layoutIfNeeded];
    
    //播放按钮
    [self.playerView addSubview:self.btnPlay];
    [self.btnPlay mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.coverView);
        make.width.height.mas_equalTo(70);
    }];
    
    [self.coverView layoutIfNeeded];
    
    //占位img
    [self.playerView addSubview:self.imgPlaceHolder];
    [self.imgPlaceHolder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.equalTo(self.playerView);
    }];
    //菊花
    self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];//设置进度轮显示类型
    [self.playerView addSubview:self.activity];
    [self.activity mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.playerView);
        make.width.height.mas_equalTo(40);
    }];
    [self.activity startAnimating];
    //////////////////////随加载状态的改变而改变
    
    self.btnPlay.hidden = YES;
    self.labTotalTime.hidden = YES;
    self.labCurrentTime.hidden = YES;
    self.slider.hidden = YES;
    //需要在竖屏下隐藏上方返回按钮和资料名称文字
    self.btnBack.hidden = YES;
    self.labName.hidden = YES;
    
    
}

//加载状态发生改变的时候切换
-(void)changeState{
    //改变隐藏的状态
    self.labCurrentTime.hidden = !self.labCurrentTime.hidden;
    self.labTotalTime.hidden = !self.labTotalTime.hidden;
    self.slider.hidden = !self.slider.hidden;
    _btnPlay.hidden = !_btnPlay.hidden;
    
    if (!self.isFullScreenNow) {
        self.btnBack.hidden = YES;
        self.labName.hidden = YES;
    }
}
#pragma mark-btn按钮事件
//点击了返回按钮
-(void)back:(UIButton *)sender{
    NSLog(@"点击了返回按钮");
//    if (self.XYPlayerBackBlock) {
//        self.XYPlayerBackBlock();
//    }
    [self changeToFullScreen:NO];
//    self.isFullScreenNow = NO;
}

//暂停/播放
- (void)play:(UIButton *)sender{
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hide) object:nil];
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [self.player pause];
    }else{
        [self.player play];
    }
    [self performSelector:@selector(hide) withObject:nil afterDelay:4];
}

//显示字幕
- (void)showSubtitle:(UIButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        self.subtitleLab.hidden = YES;
    }else{
        self.subtitleLab.hidden = NO;
    }
}

BOOL _hideTool;
#pragma mark-点击了playerView
-(void)playerViewTap:(UITapGestureRecognizer *)recognizer{
    
    //每次点击取消还在进程中的隐藏方法
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hide) object:nil];
    
    _hideTool = !_hideTool;
    
    [UIView animateWithDuration:0.25 animations:^{
        if (_hideTool) {
            self.coverView.alpha = 0;
        }else{
            self.coverView.alpha = 1;
        }
    } completion:^(BOOL finished) {
        if (_hideTool) {
            self.coverView.hidden = YES;
            self.btnPlay.hidden = YES;
        }else{
            self.coverView.hidden = NO;
            self.btnPlay.hidden = NO;
            //如果最后没隐藏,在调用隐藏的代码
            [self performSelector:@selector(hide) withObject:nil afterDelay:4];
        }
    }];
}

#pragma mark-隐藏cover
- (void)hide{
    [UIView animateWithDuration:0.25 animations:^{
        self.coverView.alpha = 0;
    }completion:^(BOOL finished) {
        self.coverView.hidden = YES;
        self.btnPlay.hidden = YES;
        _hideTool = YES;
    }];
}


#pragma mark-touchBengan
CGPoint startP;
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
//    NSLog(@"touchbegan=======%d",_hideTool);
    startP = [[touches anyObject] locationInView:self.playerView];
    
    if (!_hideTool) {
        [self hide];
    }
}

#pragma mark-点击滑块
-(void)sliderTap:(UITapGestureRecognizer *)tap{
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hide) object:nil];
    
    UISlider * slider = (UISlider *)tap.view;
    
    CGPoint point = [tap locationInView:_slider];
    
    [_slider setValue:point.x/_slider.bounds.size.width*1 animated:YES];
    
    _player.currentPlaybackTime = slider.value*_player.duration;
    
    [self performSelector:@selector(hide) withObject:nil afterDelay:4];
    
}

#pragma mark-滑块值发生改变
-(void)sliderValuechange:(UISlider *)sender{
    
    NSLog(@"sliderValuechange");
    
    //取消收回工具栏的动作
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hide) object:nil];
    
    _player.currentPlaybackTime = sender.value*_player.duration;
    
    [self performSelector:@selector(hide) withObject:nil afterDelay:4];
    
}

BOOL _hideToolbar;
#pragma mark-更新方法
- (void)updateTime{
    //    NSLog(@"---video定时器方法---");
    _labCurrentTime.text =[self TimeformatFromSeconds:self.player.currentPlaybackTime];
    
    CGFloat current = self.player.currentPlaybackTime;
    CGFloat total = self.player.duration;
    //    CGFloat able = self.player.playableDuration;
    [_slider setValue:current/total animated:YES];
    
    self.totalVideoTime = total;
}

NSTimer * timer;

#pragma mark-加载状态改变
- (void)loadStateDidChange:(NSNotification*)notification {
    IJKMPMovieLoadState loadState = _player.loadState;
    
    if ((loadState & IJKMPMovieLoadStatePlaythroughOK) != 0) {
        NSLog(@"LoadStateDidChange: IJKMovieLoadStatePlayThroughOK: %d\n",(int)loadState);
        [self.activity stopAnimating];
        _labTotalTime.text =[NSString stringWithFormat:@"%@",[self TimeformatFromSeconds:self.player.duration]];
        
        
    }else if ((loadState & IJKMPMovieLoadStateStalled) != 0) {
        NSLog(@"loadStateDidChange: IJKMPMovieLoadStateStalled: %d\n", (int)loadState);
        [self.activity startAnimating];
        
    } else {
        NSLog(@"loadStateDidChange: ???: %d\n", (int)loadState);
    }
}

#pragma mark-播放状态改变
- (void)moviePlayBackFinish:(NSNotification*)notification {
    int reason =[[[notification userInfo] valueForKey:IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
    switch (reason) {
        case IJKMPMovieFinishReasonPlaybackEnded:
            NSLog(@"playbackStateDidChange: 播放完毕: %d\n", reason);
//            [LGAlert showStatus:@"视频播放结束"];
            
            break;
            
        case IJKMPMovieFinishReasonUserExited:
            NSLog(@"playbackStateDidChange: 用户退出播放: %d\n", reason);
            break;
            
        case IJKMPMovieFinishReasonPlaybackError:
            NSLog(@"playbackStateDidChange: 播放出现错误: %d\n", reason);
//            [LGAlert showStatus:@"视频播放出错~"];
            
#pragma mark-播放出现错误,需要添重新加载播放视频的按钮

            break;
            
        default:
            NSLog(@"playbackPlayBackDidFinish: ???: %d\n", reason);
            break;
    }
}

- (void)mediaIsPreparedToPlayDidChange:(NSNotification*)notification {
    NSLog(@"mediaIsPrepareToPlayDidChange\n");
    [self.activity stopAnimating];
    
    [self.imgPlaceHolder removeFromSuperview];
    
    [self changeState];
    
    
}

- (void)moviePlayBackStateDidChange:(NSNotification*)notification {
    
    if (self.player.playbackState==IJKMPMoviePlaybackStatePlaying) {
        //视频开始播放的时候开启计时器
        NSLog(@"开始播放");
        self.subtitleLab.text = @"";
        [self stopPlayerTimer];
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
        
        [self performSelector:@selector(hide) withObject:nil afterDelay:4];
        
    }
    
    switch (_player.playbackState) {
        case IJKMPMoviePlaybackStateStopped:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: stoped", (int)_player.playbackState);
            
            [self.player pause];
            _btnPlay.selected = YES;
//            [LGAlert showStatus:@"视频播放结束"];
            [timer invalidate];
            timer = nil;
            
            break;
            
        case IJKMPMoviePlaybackStatePlaying:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: playing", (int)_player.playbackState);
            
            break;
            
        case IJKMPMoviePlaybackStatePaused:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: paused", (int)_player.playbackState);
            
            
            
            break;
            
        case IJKMPMoviePlaybackStateInterrupted:
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: interrupted", (int)_player.playbackState);
            break;
            
        case IJKMPMoviePlaybackStateSeekingForward:
        case IJKMPMoviePlaybackStateSeekingBackward: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: seeking", (int)_player.playbackState);
            break;
        }
            
        default: {
            NSLog(@"IJKMPMoviePlayBackStateDidChange %d: unknown", (int)_player.playbackState);
            break;
        }
    }
}

#pragma mark-观察视频播放状态

- (void)installMovieNotificationObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loadStateDidChange:)
                                                 name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                               object:_player];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackFinish:)
                                                 name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(mediaIsPreparedToPlayDidChange:)
                                                 name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                               object:_player];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackStateDidChange:)
                                                 name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                               object:_player];
    
}

- (void)removeMovieNotificationObservers {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMoviePlayerLoadStateDidChangeNotification
                                                  object:_player];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMoviePlayerPlaybackDidFinishNotification
                                                  object:_player];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification
                                                  object:_player];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:IJKMPMoviePlayerPlaybackStateDidChangeNotification
                                                  object:_player];
    
}

#pragma mark-公共方法
- (NSString*)TimeformatFromSeconds:(NSInteger)seconds{
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    if ([str_hour isEqualToString:@"00"]) {
        return [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    }else{
        return [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    }
//    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
//    return format_time;
}

//从图片
- (UIImage*) createImageWithColor:(UIColor*) color{
    CGRect rect=CGRectMake(0,0,15,15);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

- (UIImage *)circleImageWithImage:(UIImage *)oldImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor{
    // 1.加载原图
 
    // 2.开启上下文
    CGFloat imageW = oldImage.size.width + 22 * borderWidth;
    CGFloat imageH = oldImage.size.height + 22 * borderWidth;
    CGSize imageSize = CGSizeMake(imageW, imageH);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    
    // 3.取得当前的上下文,这里得到的就是上面刚创建的那个图片上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 4.画边框(大圆)
    [borderColor set];
    CGFloat bigRadius = imageW * 0.5; // 大圆半径
    CGFloat centerX = bigRadius; // 圆心
    CGFloat centerY = bigRadius;
    CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
    CGContextFillPath(ctx); // 画圆。As a side effect when you call this function, Quartz clears the current path.
    
    // 5.小圆
    CGFloat smallRadius = bigRadius - borderWidth;
    CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
    // 裁剪(后面画的东西才会受裁剪的影响)
    CGContextClip(ctx);
    
    // 6.画图
    [oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
    
    // 7.取图
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 8.结束上下文
    UIGraphicsEndImageContext();
    
    return newImage;
}

#pragma mark -setter
- (void)setResName:(NSString *)resName{
    _resName = resName;
    self.labName.text = resName;
}

#pragma mark -补充方法
- (void)stopPlayerTimer{
    NSLog(@"销毁播放器页面定时器");
    //关闭定时器
    [timer invalidate];
    timer = nil;
}

- (void)destroyPlayer{
    [self stopPlayerTimer];
    [self.player shutdown];
}
//暂停播放
- (void)pauseXYVideo{
    if (self.isListenType) {
    
    }else{
        [self.player pause];
    }
    
    self.btnPlay.selected = YES;
}

//恢复播放
- (void)replyXYVideo{
    [self.player play];
    self.btnPlay.selected = NO;
}
//获取视频总时长
- (CGFloat)getTotalVideoTime{
    return self.totalVideoTime;
}

#pragma mark -lazy
- (UIButton *)btnBack{
    if (!_btnBack) {
        _btnBack = [[UIButton alloc]init];
//        _btnBack.backgroundColor = [UIColor redColor];
        [_btnBack setImage:[UIImage imageNamed:@"ijk_back"] forState:UIControlStateNormal];
        [_btnBack addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _btnBack;
}
- (UILabel *)labName{
    if (!_labName) {
        _labName = [[UILabel alloc]init];
        _labName.font = [UIFont systemFontOfSize:14];
        _labName.textColor = [UIColor redColor];
    }
    return _labName;
}
-(UIButton *)btnSubtitle{
    if (!_btnSubtitle) {
        _btnSubtitle = [UIButton new];
        [_btnSubtitle setImage:[UIImage imageNamed:@"xy_ijkPlayer_wordOpen"] forState:UIControlStateNormal];
        [_btnSubtitle setImage:[UIImage imageNamed:@"xy_ijkPlayer_wordClose"] forState:UIControlStateSelected];
        [_btnSubtitle addTarget:self action:@selector(showSubtitle:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _btnSubtitle;
}

- (UILabel *)labCurrentTime{
    if (!_labCurrentTime) {
        _labCurrentTime = [[UILabel alloc]init];
        _labCurrentTime.font = [UIFont systemFontOfSize:12];
        _labCurrentTime.text = @"00:00";
        _labCurrentTime.textColor = [UIColor whiteColor];
        _labCurrentTime.textAlignment = NSTextAlignmentLeft;
    }
    return _labCurrentTime;
}

- (UILabel *)labTotalTime{
    if (!_labTotalTime) {
        _labTotalTime = [[UILabel alloc]init];
        _labTotalTime.font = [UIFont systemFontOfSize:12];
        _labTotalTime.text = @"00:00";
        _labTotalTime.textColor = [UIColor whiteColor];
        _labTotalTime.textAlignment = NSTextAlignmentLeft;
    }
    return _labTotalTime;
}

- (UIButton *)btnFullScreen{
    if (!_btnFullScreen) {
        _btnFullScreen = [[UIButton alloc]init];
        [_btnFullScreen setImage:[UIImage imageNamed:@"studyStu_shuping"] forState:UIControlStateNormal];
        [_btnFullScreen setImage:[UIImage imageNamed:@"studyStu_hengping"] forState:UIControlStateSelected];
        
        [_btnFullScreen addTarget:self action:@selector(fullScreen:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _btnFullScreen;
}

- (UISlider *)slider{
    if (!_slider) {
        _slider = [[UISlider alloc]init];
        _slider.userInteractionEnabled = YES;
        _slider.continuous = YES;//设置为no，只有在手指离开的时候才调用valueChange
        [_slider addTarget:self action:@selector(sliderValuechange:) forControlEvents:UIControlEventValueChanged];
        UITapGestureRecognizer *slideTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(sliderTap:)];
        [_slider addGestureRecognizer:slideTap];
    }
    return _slider;
}

- (UIImageView *)imgListen{
    if (!_imgListen) {
        _imgListen = [[UIImageView alloc]initWithFrame:CGRectZero];
        _imgListen.image = [UIImage imageNamed:@"launch3"];
    }
    return _imgListen;
}

- (BrightnessVolumeView *)systemView{
    if (!_systemView) {
        _systemView = [BrightnessVolumeView new];
    }
    return _systemView;
}

- (UIImageView *)imgPlaceHolder{
    if (!_imgPlaceHolder) {
        _imgPlaceHolder = [UIImageView new];
        _imgPlaceHolder.image = [UIImage imageNamed:@"KQ_playViewblackBG"];
    }
    return _imgPlaceHolder;
}

- (UIView *)coverView{
    if (!_coverView) {
        _coverView = [[UIView alloc]init];
        _coverView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.1];
    }
    return _coverView;
}

- (UIButton *)btnPlay{
    if (!_btnPlay) {
        _btnPlay = [[UIButton alloc]init];
        [_btnPlay setImage:[UIImage imageNamed:@"studyStu_bofang"] forState:UIControlStateNormal];
        [_btnPlay setImage:[UIImage imageNamed:@"studyStu_zanting"] forState:UIControlStateSelected];
        [_btnPlay addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnPlay;
}

@end
